package com.nakamachizu.util;

import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slim3.controller.ControllerConstants;
import org.slim3.util.LocaleUtil;

public class ResourceUtil {
    public static ResourceBundle getResourceBundle(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        Locale locale = null;
        if(session != null){
            Object o = session.getAttribute(ControllerConstants.LOCALE_KEY);
            if (o instanceof String) {
                locale = LocaleUtil.parse((String) o);
            } else if (o instanceof Locale) {
                locale = (Locale) o;
            }
        }
        
        if(locale == null){
            locale = LocaleUtil.parse("ja");
        }
        
        return ResourceBundle.getBundle(
            ControllerConstants.DEFAULT_LOCALIZATION_CONTEXT,
            locale,
            Thread
                .currentThread()
                .getContextClassLoader());
    }
    
    public static ResourceBundle getResourceBundle(HttpServletRequest request, String resourceName){
        HttpSession session = request.getSession(false);
        Locale locale = null;
        if(session != null){
            Object o = session.getAttribute(ControllerConstants.LOCALE_KEY);
            if (o instanceof String) {
                locale = LocaleUtil.parse((String) o);
            } else if (o instanceof Locale) {
                locale = (Locale) o;
            }
        }
        
        if(locale == null){
            locale = LocaleUtil.parse("ja");
        }
        
        return ResourceBundle.getBundle(
            resourceName,
            locale,
            Thread
                .currentThread()
                .getContextClassLoader());
    }
}
